package org.check.potimize.business;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.check.Util.LoadUtil;
import org.check.VO.DBParaVO;

public class MapLoader {
	static Connection conn = null;
	public static String startDateRegex = "@startDate";
	public static String endDateRegex = "@endDate";
	
	public static ResultSet load(DBParaVO vo) {
		try {
			conn = LoadBaseCourseUser.connPool.getCurrentConnecton();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		//System.out.println(conn.toString());
		String sqlStr = LoadUtil.getSql(vo);
		if(vo.getTablename().equalsIgnoreCase("courseuser")){
			String idFilter = "where course_id like '"+LoadBaseCourseUser.filter+"'";
			sqlStr = sqlStr.replaceAll("@filter", idFilter);
			sqlStr = sqlStr.replaceAll("@course_type", vo.getCourseType());
			sqlStr = sqlStr.replaceAll("@select", vo.getSelectedCols());
			sqlStr = sqlStr.replaceAll(startDateRegex, vo.getCourseStartDate());
	        sqlStr = sqlStr.replaceAll(endDateRegex, vo.getCourseEndDate());
		}
		else{
			sqlStr = sqlStr.replaceAll(startDateRegex, vo.getStartDate());
	        sqlStr = sqlStr.replaceAll(endDateRegex, vo.getEndDate());
		}
		/*System.out.println("------------debug-----------");
		System.out.println(sqlStr);
		System.out.println("------------debug-----------");*/
		Statement stmt;
		ResultSet rs = null;
		try {
			stmt = conn.createStatement();		
			rs = stmt.executeQuery(sqlStr);	
			LoadBaseCourseUser.connPool.releaseConn(conn);
		} catch (SQLException e) {
			SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = Calendar.getInstance().getTime();
			String dateStr = format.format(date);
			System.out.println(dateStr+"****"+"error when query on table:"+vo.getTablename());
			e.printStackTrace();
			LoadBaseCourseUser.isError = true;
		}
		//System.out.println("table search on "+ vo.getTablename()+Calendar.getInstance().getTimeInMillis());
		return rs;
	}
	
	public static HashMap<String, String> getMapList(ResultSet rs){
		ResultSetMetaData data = null;
		HashMap<String, String> map = new HashMap<String, String>(); 			
		try
		{	
			data = rs.getMetaData();    
	        while (rs.next()) {  
                String c1 = data.getColumnName(1);  
                String v1 = rs.getString(c1); 
                String c2 = data.getColumnName(2);
                String v2 = rs.getString(c2); 
                map.put(v1, v2);  
	        }  
		}catch (SQLException e) {
			SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = Calendar.getInstance().getTime();
			String dateStr = format.format(date);
			System.out.println(dateStr+"****"+"error when execute MAP set ");
			e.printStackTrace();
		}	
		return map;
	}
	
	@SuppressWarnings("unchecked")
	public static List resultSetToList(ResultSet rs, Class cls)throws Exception {
			//ȡ��Method 
	        Method[] methods = cls.getDeclaredMethods(); 
			List lst = new ArrayList();
			// ���ڻ�ȡ����������������
			ResultSetMetaData meta = rs.getMetaData();
			Object obj = null;
			while (rs.next()) {
				// ��ȡformbeanʵ������
				obj = cls.newInstance(); // ��Class.forName����ʵ���������new����ʵ�����������кܴ�����ģ���Ҫ��JVM���ȴ���������в����࣬Ȼ����ʵ������������ִ�����еľ�̬��������new�������½�һ������ʵ��
				// ѭ����ȡָ���е�ÿһ�е���Ϣ
				for (int i = 1; i <= meta.getColumnCount(); i++) {
					// ��ǰ����
					String colName = meta.getColumnName(i);
					
					// ���÷�����
					String setMethodName = "set" + colName;
					  
					
					 //����Method 
	                for (int j = 0; j < methods.length; j++) { 
	                    if (methods[j].getName().equalsIgnoreCase(setMethodName)) { 
	                        setMethodName = methods[j].getName(); 
	                        
	                    	// ��ȡ��ǰλ�õ�ֵ������Object����
	                        Object value = rs.getObject(colName); 
	                        if(value == null){
	                        	continue;
	                        }

	                        //ʵ��Set���� 
	                        try { 
	                        	//// ���÷����ȡ����
	                            //JavaBean�ڲ����Ժ�ResultSet��һ��ʱ�� 
	                        	String inputvalue = value.toString();
	                            Method setMethod = obj.getClass().getMethod( 
	                                    setMethodName, inputvalue.getClass()); 
	                            setMethod.invoke(obj, inputvalue); 
	                        } catch (Exception e) { 
	                            //JavaBean�ڲ����Ժ�ResultSet�в�һ��ʱ��ʹ��String������ֵ�� 

	                        	SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	                			Date date = Calendar.getInstance().getTime();
	                			String dateStr = format.format(date);
	                			System.out.println(dateStr+"****"+"error when execute OBJ set ");
	                           e.printStackTrace();
	                        } 
	                    } 
	                } 
				}
				lst.add(obj);
			}

			return lst;
		
	}
}
